package club.kynb.mall.application.context;

import club.kynb.mall.application.model.model.dto.TokenDTO;
import club.kynb.mall.basic.dto.HeaderDTO;
import club.kynb.mall.user.model.dto.UserDTO;
import lombok.Data;
import org.pizza.common.web.exception.Errors;
import org.pizza.model.Model;
import org.pizza.util.Checker;

/**
 * @author kynb_club@163.com
 * @since 2021/6/24 9:50 上午
 */
@Data
public class MallUserContext implements Model {
    private UserDTO userDTO;
    private TokenDTO tokenDTO;

    private static final ThreadLocal<MallUserContext> CURRENT = new ThreadLocal<>();
    private static final ThreadLocal<HeaderDTO> CURRENT_HEAD = new ThreadLocal<>();

    public static void clear() {
        CURRENT.remove();
        CURRENT_HEAD.remove();
    }

    public static void build(MallUserContext context) {
        CURRENT.set(context);
    }

    public static void build(HeaderDTO headerDTO) {
        CURRENT_HEAD.set(headerDTO);
    }

    public static HeaderDTO getHeader(){
        final HeaderDTO headerDTO = CURRENT_HEAD.get();
        Checker.ifNullThrow(headerDTO, () -> Errors.SYSTEM.exception("很遗憾，登录信息丢失，请重新登录~~"));
        return headerDTO;
    }

    public static MallUserContext get(boolean required) {
        final MallUserContext mallUserContext = CURRENT.get();
        if (required) {
            Checker.ifNullThrow(mallUserContext, () -> Errors.SYSTEM.exception("很遗憾，登录信息丢失，请重新登录~~"));
        }
        return mallUserContext;
    }
}
